import qs from 'qs'
import axios from 'axios'
import {
    MessageBox,
    Loading
} from 'element-ui';
const TIMEOUT = 30 * 1000

const loadObj = (function () {
    var showId, hideId, loadingInstance; // 打开定时器Id，关闭Id, Loading本身
    return {
        show() {
            if (hideId) { // 如果 有新的接口发送，就关闭hideId定时器，使loading 继续打开
                clearTimeout(hideId)
                hideId = ''
            }
            if (showId) return //如果load已经打开 或者正在等待打开，则不进行操作
            showId = setTimeout(() => {
                loadingInstance = Loading.service()
            }, 10)
        },
        hide() {
            if (!hideId) {
                hideId = setTimeout(() => {
                    hideId = ''
                    showId =
                        loadingInstance && loadingInstance.close()
                }, 50)
            }
        },
        close() { // 
            clearTimeout(showId)
        }
    }
})()
// function fGetUrl() {
//     if (process.env.NODE_ENV === 'development') { //开发环境
//         return process.env.DEV_URL;
//     } else if (process.env.NODE_ENV === 'production') {
//         /*上线后更改*/
//         return process.env.PROD_URL;
//     }
// }
function download(fileName, data) {
    const blob = new Blob([data])
    if ('msSaveOrOpenBlob' in navigator) {
        window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) //创建下载链接
        downloadElement.href = href
        downloadElement.download = fileName // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        setTimeout(() => {
            document.body.removeChild(downloadElement)
            window.URL.revokeObjectURL(href) // 释放blob对象
        }, 100)
    }
}

const ajax = axios.create({
    baseURL: process.env.VUE_APP_BASEURL, // url = base url + request url
    withCredentials: false, // send cookies when cross-domain requests
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' // 默认配置
    },
    transformRequest: [function (data, headers) { // 处理请求数据，运行在拦截器之后
        try {
            // 这里主要处理 文件上传的数据处理
            if (headers['Content-type'] == 'multipart/form-data') {
                let form = new FormData()
                for (let k in data) {
                    let v = data[k]
                    if (Object.prototype.toString.call(v) === '[]Object Array') {
                        v.forEach(item => {
                            form.append(k, item)
                        })
                    } else {
                        form.append(k, v)
                    }
                }
                data = form
            } else if (headers['Content-type'].indexOf('application/x-www-form-urlencoded') > -1) {
                data = qs.stringify(data) // 处理链式请求 数据
            } else {
                // 这里处理 application/json  时需要格式化
                data = JSON.stringify(data)
            }
            return data
        } catch (err) {
            MessageBox({
                title: '错误提示',
                message: err,
                type: 'error'
            })
        }
    }],
    paramsSerializer: function (params) {
        // 处理get请求数据
        return qs.stringify(params)
    },
    timeout: TIMEOUT // request timeout
})

ajax.interceptors.request.use(function (config) { //前端请求拦截器
    const {
        method,
        data
    } = config
    if (method === 'get') {
        config.params = {
            ...data
        }
    }
    if (!(data && data.current)) { // 由于table 自带 loading  除去
        loadObj.show()
    }
    if (config.type === 'form') { //处理上传文件
        config.headers['Content-Type'] = "multipart/form-data"
    } else if (config.type === 'json') { // 后端使用 @requestBody 用于复杂对象
        config.headers['Content-Type'] = "application/json;charset=utf-8"
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});
ajax.interceptors.response.use(function (response) { //前端响应拦截器
    if (response.headers['content-type'].indexOf('application/octet-stream') != -1) { //下载
        var fileName = response.headers['original-filename']
        fileName = decodeURIComponent(escape(fileName))
        download(fileName, response.data)
    }
    loadObj.hide()
    return response;
}, function (error) {
    loadObj.hide()
    MessageBox({
        title: '错误提示',
        message: error,
        type: 'error'
    })
    return Promise.reject(error);
});

export default ajax;
